package com.digiwin.dap.middleware.trace;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.boot.actuate.logging.LogFileWebEndpoint;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.Arrays;
import java.util.Optional;

@WebEndpoint(
        id = "logfile"
)
public class AutoLogFileWebEndpoint extends LogFileWebEndpoint {
    private static final Log logger = LogFactory.getLog(LogFileWebEndpoint.class);
    private final Environment environment;
    private File errorFile;

    public AutoLogFileWebEndpoint(Environment environment) {
        super(environment);
        this.environment = environment;
        String path = environment.getProperty("logging.path");

        if (!StringUtils.hasText(path)) {
            path = ".logs";
        }
        String errorPath = path + "/" + "error/test";
        errorFile = new File(errorPath);
        createMissingParentDirectories(errorFile);
        File logFile = new File(path);
        File[] files = logFile.listFiles();
        for (File file : files) {
            if (file.isDirectory() && file.getName().toLowerCase().equals("error")) {
                errorFile = file;
                break;
            }
        }

    }


    @Override
    @ReadOperation
    public Resource logFile() {
        Resource logFileResource = this.getLogFileResource();
        return logFileResource != null && logFileResource.isReadable() ? logFileResource : null;
    }

    static boolean createMissingParentDirectories(File file) {

        File parent = file.getParentFile();
        if (parent == null) {
            return true;
        } else {
            parent.mkdirs();
            return parent.exists();
        }
    }

    private Resource getLogFileResource() {
        try {
            if (errorFile.exists()) {
                File[] fileList = errorFile.listFiles();
                if (fileList != null && fileList.length > 0) {
                    Optional<File> lastModifiedFile = Arrays.stream(fileList).max((file1, file2) -> {
                        return file1.lastModified() > file2.lastModified() ? 1 : -1;
                    });
                    if (lastModifiedFile.isPresent()) {
                        return new FileSystemResource(lastModifiedFile.get());
                    }
                }
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }
}
